import express from 'express'
import bodyParser from 'body-parser'
// import {parseComponent} from 'vue-template-compiler'
import fs from 'fs'
import path from 'path'

const app = express();

//设置跨域请求头
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

/**
 * 文件目录解析
 * @param pathArray
 * @returns {Promise<unknown>}
 */
function filesParse(pathArray) {
  return new Promise((resolve, reject) => {
    fs.readdir(pathArray, (err, files) => {
      if (err) {
        reject('解析失败！')
      } else {
        resolve(files);
      }
    })

  })
}

/**
 * 文件内容读取
 * @param path
 * @returns {Promise<unknown>}
 */
function readFile(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', function (err, dataStr) {
      if (err) {
        reject('读取失败！' + err.message);
      }
      resolve(dataStr);
    })
  })

}

/**
 * 文件写入
 * @param path
 * @param content
 * @returns {Promise<unknown>}
 */
function writeFile(path, content) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, content, function (err) {
      if (err) {
        return console.log('文件写入失败！' + err.message);
      }
      console.log('文件写入成功！');
    })
  })
}

app.post('/compiler', async function (req, res) {
  //最终解析返回的json数据
  let parseJson = {};
  //开始遍历的文件夹路径
  const initPath = '../src/pages/api';
  //解析api下的文件夹目录
  const pathArray = path.resolve(initPath);
  const initPathFiles = await filesParse(pathArray);
  for (let i = 0; i < initPathFiles.length; i++) {
    const apiPath = `${initPath}/${initPathFiles[i]}`;
    const apiFilesPath = path.resolve(apiPath);
    const apiFiles = await filesParse(apiFilesPath);
    parseJson[initPathFiles[i]] = {};
    for (let j = 0; j < apiFiles.length; j++) {
      const examplePath = `${initPath}/${initPathFiles[i]}/${apiFiles[j]}`;
      const exampleFilesPath = path.resolve(examplePath);
      const examplesFiles = await filesParse(exampleFilesPath);
      //默认创建api属性存放组件解析的信息,examples存放示例代码的源码信息
      parseJson[initPathFiles[i]][apiFiles[j]] = {
        api: {
          props: [],
          methods: [],
          slots: [],
          events: []
        },
        examples: {}
      };

      //读取组件 props、emit、function内容
      let componentfileContent = await readFile(`../src/packages/${initPathFiles[i]}/${apiFiles[j]}/index.vue`);
      //提取注释正则
      const reg = /\/\*([\s\S]*?)\*\//g;
      let resultArr = componentfileContent.toString().replace(/\n/g, "").replace(/\\s+/g, '').match(reg)
      let obj = parseJson[initPathFiles[i]][apiFiles[j]].api;
      resultArr.forEach((item) => {
        if (item.indexOf('@props') !== -1) {
          let note = item.replace('/*', '').replace('*/', '').split('*');
          let propInfo = {name: '-', des: '-', type: '-', default: '-'};
          note.forEach((noteItem) => {
            if (noteItem.trim() !== '') {
              if (noteItem.includes('@props')) {
                propInfo.name = noteItem.replace('@props', '').trim();
              } else if (noteItem.includes('@type')) {
                propInfo.type = noteItem.replace('@type', '').trim();
              } else if (noteItem.includes('@default')) {
                propInfo.default = noteItem.replace('@default', '').trim();
              } else {
                propInfo.des = noteItem.trim();
              }
            }
          })
          obj.props.push(propInfo);
        }
      })


      for (let k = 0; k < examplesFiles.length; k++) {
        //排除api首页文件index.vue
        if (examplesFiles[k] !== 'index.vue') {
          //获取示例文件路径
          const exampleFilePath = `${initPath}/${initPathFiles[i]}/${apiFiles[j]}/${examplesFiles[k]}`;
          //读取示例文件内容
          parseJson[initPathFiles[i]][apiFiles[j]].examples[examplesFiles[k].replace('example', '').replace('.vue', '').toLowerCase()] = await readFile(exampleFilePath);
        }
      }
    }
  }
  res.send('APi解析成功！内容请查看src/assets/componentsApi.json');
  //写入api内容
  await writeFile('../src/assets/componentsApi.json', JSON.stringify(parseJson));
})

app.post('/test', function (req, res) {
  console.log(req)
  res.send("{\"error\":\"0\"}");
})

app.get('/test1', function (req, res) {
  console.log(req)
  res.send("{\"error\":\"0\"}");
})

app.post('/table', function (req, res) {
  const data = {
    list: [
      {deptName: '总部', post: '财务专员', name: '', attendance: 22},
      {deptName: '研发部', post: '产品经理', name: '', attendance: 21},
      {deptName: '研发部', post: '产品经理', name: '', attendance: 19},
      {deptName: '人力资源', post: '人事总监', name: '', attendance: 22},
      {deptName: '售前', post: '大区经理', name: '', attendance: 22}
    ],
    total: 200
  }
  res.send(data);
})

app.listen(3001, () => console.log('测试API——3001端口开启...'))
